import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse() as |  string | { message: string | string[] };
    let message = '操作失败';
    if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
      message = Array.isArray(exceptionResponse.message) ? exceptionResponse.message.join(';') : exceptionResponse.message;
    } else {
      message = exceptionResponse;
    }
    response.status(status).json({
      status,
      message,
      data: null,
    });
  }
}
